from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from django.test import TestCase
from users.models import User
from admin_panel.models import SystemConfig
from rest_framework_simplejwt.tokens import RefreshToken


class SystemConfigModelTest(TestCase):
    """测试系统配置模型"""

    def setUp(self):
        """设置测试数据"""
        self.config = SystemConfig.objects.create(
            key='site_name',
            value='校园生活平台',
            config_type='system',
            description='网站名称'
        )

    def test_system_config_creation(self):
        """测试系统配置创建"""
        self.assertEqual(self.config.key, 'site_name')
        self.assertEqual(self.config.value, '校园生活平台')
        self.assertEqual(self.config.config_type, 'system')
        self.assertEqual(self.config.description, '网站名称')
        self.assertTrue(self.config.is_active)


class SystemConfigAPITest(APITestCase):
    """测试系统配置API"""

    def setUp(self):
        """设置测试数据"""
        self.admin_user = User.objects.create_user(
            username='adminuser',
            password='adminpassword',
            email='admin@example.com',
            role='admin',
            is_staff=True
        )
        # 生成管理员JWT令牌
        refresh = RefreshToken.for_user(self.admin_user)
        self.admin_access_token = str(refresh.access_token)
        self.admin_headers = {'Authorization': f'Bearer {self.admin_access_token}'}

        self.regular_user = User.objects.create_user(
            username='regularuser',
            password='regularpassword',
            email='regular@example.com',
            role='user'
        )
        # 生成普通用户JWT令牌
        refresh = RefreshToken.for_user(self.regular_user)
        self.regular_access_token = str(refresh.access_token)
        self.regular_headers = {'Authorization': f'Bearer {self.regular_access_token}'}

        self.config = SystemConfig.objects.create(
            key='site_name',
            value='校园生活平台',
            config_type='system',
            description='网站名称'
        )

    def test_admin_can_list_system_configs(self):
        """测试管理员可以列出系统配置"""
        # 管理员登录
        self.client.login(username='adminuser', password='adminpassword')
        url = reverse('system-config-list')
        response = self.client.get(url, headers=self.admin_headers)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn('data', response.data)
        self.assertEqual(len(response.data['data']), 1)
        self.assertEqual(response.data['data'][0]['key'], 'site_name')

    def test_regular_user_cannot_access_config_api(self):
        """测试普通用户无法访问系统配置API"""
        # 普通用户登录
        self.client.login(username='regularuser', password='regularpassword')
        url = reverse('system-config-list')
        response = self.client.get(url, headers=self.regular_headers)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_admin_can_update_system_config(self):
        """测试管理员可以更新系统配置"""
        # 管理员登录
        self.client.login(username='adminuser', password='adminpassword')
        url = reverse('system-config-detail', kwargs={'pk': self.config.id})
        data = {
            'value': '新校园生活平台'
        }
        response = self.client.patch(url, data, headers=self.admin_headers)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['data']['value'], '新校园生活平台')

    def test_admin_can_create_system_config(self):
        """测试管理员可以创建系统配置"""
        # 管理员登录
        self.client.login(username='adminuser', password='adminpassword')
        url = reverse('system-config-list')
        data = {
            'key': 'site_title',
            'value': '校园生活平台官网',
            'config_type': 'system',
            'description': '网站标题'
        }
        response = self.client.post(url, data, headers=self.admin_headers)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(response.data['data']['key'], 'site_title')
        self.assertEqual(SystemConfig.objects.count(), 2)
